package com.example.task4.dao;

import com.example.task4.util.DataBaseUtil;
import com.example.task4.domain.Cake;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CakeDao {
    public List<Cake> listCakes(){
        List<Cake> cakeList=new ArrayList<>();
        Connection con= DataBaseUtil.getConnection();

        String sql="select * from cakes";
        try {
            PreparedStatement stmt=con.prepareStatement(sql);
            //执行语句
            ResultSet rs = stmt.executeQuery();
            while(rs.next()){
                Cake cake=new Cake();
                //设置蛋糕ID
                cake.setId(rs.getString(1));
                //设置蛋糕名称
                cake.setName(rs.getString(2));
                //设置蛋糕描述
                cake.setDescription(rs.getString(3));
                //设置蛋糕单价
                cake.setPrice(rs.getDouble(4));
                //设置蛋糕图片
                cake.setImageUrl(rs.getString(5));
                //将蛋糕加到集合里
                cakeList.add(cake);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return cakeList;
    }
    public Cake findCakeById(String id){
        Cake cake=new Cake();
        Connection con=DataBaseUtil.getConnection();
        String sql="select * from Cakes where cake_id=?";
        try {
            PreparedStatement stmt=con.prepareStatement(sql);
            stmt.setString(1,id);
            ResultSet rs=stmt.executeQuery();
            if(rs.next()){
                cake.setId(rs.getString(1));
                cake.setName(rs.getString(2));
                cake.setDescription(rs.getString(3));
                cake.setPrice(rs.getDouble(4));
                cake.setImageUrl(rs.getString(5));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return cake;
    }
}
